#pragma once
#include "protocol.hpp"
#include "log.hpp"

class calculator {
public:
    response helper(const request &req) const {
        switch (req._op) {
            case '+':
                return response(req._x + req._y);
            case '-':
                return response(req._x - req._y);;
            case '*':
                return response(req._x * req._y);
            case '/':
                if(req._y == 0) {
                    return response(0, div_by_zero);
                }
                return response(req._x / req._y);
            case '%':
                if(req._y == 0) {
                    return response(0, mod_by_zero);
                }
                return response(req._x % req._y);
            default:
                return response(0, invalid_op);
        }
    }

    string calculate(string &package) const {
        // 处理数据
        // 解包
        string content;
        if(!decapsulate(&content, package)) {
            return "";
        }
        // 反序列化
        request req;
        req.deserializer(content);
        lg(INFO, "server decapsulate and deserializer Request: %s", content.c_str());
        // 计算
        response res = helper(req);
        // 序列化
        string packet;
        res.serializer(&packet);
        // 封装
        if(!encapsulate(&packet)) {
            return "";
        }
        lg(INFO, "server encapsulate Response: %s", packet.c_str());
        return packet;
    }
};